package com.sky.zzh.home;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.next.intf.ITaskListener;
import com.next.net.SHPost;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.widget.SHDialog.DialogItemClickListener;
import com.sky.widget.SHToast;
import com.sky.widget.sweetdialog.SweetDialog;
import com.sky.zzh.R;
import com.sky.zzh.SHApplication;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.HttpUtils;
import com.sky.zzh.util.UserInfoManager;
import com.sky.zzh.view.SHEditTextNoClear;
/**
 * 注册
 * @author skypan
 *
 */
public class RegisterActivity extends Activity implements ITaskListener{

	private Button mBtnRegister;
	private SHEditTextNoClear mEtPwd1,mEtPwd2;
	private ImageView mIvPhoto,mBtnBack;
	private SHPost registerTask;//注册请求
	private final int TAKE_PICTURE = 1;// 拍照
	private final int CHOOSE_PICTURE = 2;// 相册
	private String picPath;
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case 0:
				requestRegister();
				//上传成功
				break;
			case 1:
				SHToast.showToast(RegisterActivity.this, "图片格式不支持");
				break;
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		SHApplication.getInstance().addActivity(this);
		
		mBtnBack = (ImageView) findViewById(R.id.btn_back);
		mBtnRegister = (Button) findViewById(R.id.btn_register);
		mEtPwd1 = (SHEditTextNoClear) findViewById(R.id.et_pwd1);
		mEtPwd2 = (SHEditTextNoClear) findViewById(R.id.et_pwd2);
		mIvPhoto = (ImageView) findViewById(R.id.iv_photo);
		mBtnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		mIvPhoto.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final String[] items = new String[]{"相册","拍照"};
				SHDialog.showActionSheet(RegisterActivity.this, "选择照片来源", items, new DialogItemClickListener() {
					
					@Override
					public void onSelected(String result) {
						// TODO Auto-generated method stub
						if(result.equals(items[0])){
							Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							startActivityForResult(intent, CHOOSE_PICTURE);
						}else{
							Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "zzh.png"));
							openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
							startActivityForResult(openCameraIntent, TAKE_PICTURE);
						}
					}
				});
			}
		});
		
		mBtnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				if(CommonUtil.isEmpty(mEtPwd1.getText().toString().trim()) || CommonUtil.isEmpty(mEtPwd2.getText().toString().trim())){
					SHToast.showToast(RegisterActivity.this, "请输入密码");
					return;
				}
				
				if(!mEtPwd1.getText().toString().trim().equals(mEtPwd2.getText().toString().trim())){
					SHToast.showToast(RegisterActivity.this, "密码不一致");
					return;
				}
				if(picPath != null){
					SHDialog.ShowProgressDiaolg(RegisterActivity.this);
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							String result = HttpUtils.submitPostImg(ConfigDefinition.URL+"file/UploadFile/"+UserInfoManager.getInstance().getUserId(), picPath);
							System.out.println("result:"+result);
							try {
								JSONObject json = new JSONObject(result);
								if("200".equals(json.optString("ReturnCode"))){
//									Intent intent = new Intent(RegisterActivity.this,ZZHMainActivity.class);
//									startActivity(intent);
									mHandler.sendEmptyMessage(0);
								}else{
									mHandler.sendEmptyMessage(1);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}).start();
				}else{
					requestRegister();
				}
//				Intent intent = new Intent(RegisterActivity.this,ZZHMainActivity.class);
//				startActivity(intent);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			
			BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
			bitmapOptions.inSampleSize = 3;
			
			switch(requestCode){
			case TAKE_PICTURE://拍照
				
				picPath = Environment.getExternalStorageDirectory() + "/zzh.png";
				Bitmap bitmap_tack = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/zzh.png", bitmapOptions);
				mIvPhoto.setImageBitmap(bitmap_tack);
//				SHDialog.ShowProgressDiaolg(this);
//				new Thread(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						String result_take = HttpUtils.submitPostImg(ConfigDefinition.URL+"file/UploadFile/"+UserInfoManager.getInstance().getUserId(), Environment.getExternalStorageDirectory() + "/zzh.png");
//						System.out.println("result:"+result_take);
//						mHandler.sendEmptyMessage(0);
//					}
//				}).start();
				break;
			case CHOOSE_PICTURE://相册
				Uri originalUri = data.getData();
				String[] filePathColumns = { MediaStore.Images.Media.DATA };
				Cursor c = getContentResolver().query(originalUri, filePathColumns, null, null, null);
				c.moveToFirst();
				int columnIndex = c.getColumnIndex(filePathColumns[0]);
				final String picturePath = c.getString(columnIndex);
				picPath = picturePath;
				c.close();
				Bitmap bitmap_choose = BitmapFactory.decodeFile(picturePath, bitmapOptions);
				mIvPhoto.setImageBitmap(bitmap_choose);
				break;
			}
		}
	}



	private void requestRegister(){
		SHDialog.ShowProgressDiaolg(this);
		registerTask = new SHPost();
		registerTask.setUrl(ConfigDefinition.URL+"user/UserRegister");
		registerTask.setListener(this);
		registerTask.getTaskArgs().put("UserValidationServer", getIntent().getStringExtra("loginType"));
		registerTask.getTaskArgs().put("UserIdOriginal", getIntent().getStringExtra("openid"));
		registerTask.getTaskArgs().put("CellPhone", getIntent().getStringExtra("phone"));
		registerTask.getTaskArgs().put("Email", "");
		registerTask.getTaskArgs().put("Password", mEtPwd1.getText().toString().trim());
		registerTask.start();
	}
	
	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		// TODO Auto-generated method stub
		SHDialog.dismissProgressDiaolg();
		System.out.println(task.getResult().toString());
		JSONObject json = new JSONObject(task.getResult().toString());
		if ("200".equals(json.optString("ReturnCode"))) {
			UserInfoManager.getInstance().setUserId(json.optString("UserID"));
			UserInfoManager.getInstance().sync(this, true);
			Intent intent = new Intent(RegisterActivity.this,ZZHMainActivity.class);
			startActivity(intent);
			finish();
		}else if("10005".equals(json.optString("ReturnCode"))){
			new SweetDialog(RegisterActivity.this, SweetDialog.ERROR_TYPE).setTitleText("提示").setContentText("用户已存在").show();
		}else{
			new SweetDialog(RegisterActivity.this, SweetDialog.ERROR_TYPE).setTitleText("提示").setContentText(json.optString("ErrorMessage")).show();
		}
	}

	@Override
	public void onTaskFailed(SHTask task) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTaskTry(SHTask task) {
		// TODO Auto-generated method stub
		
	}

}
